import {
  _decorator,
  BoxCollider2D,
  CCString,
  Component,
  director,
  instantiate,
  Label,
  log,
  math,
  Node,
  Prefab,
  UITransform,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("GameManager")
export class GameManager extends Component {
  @property(Prefab)
  public workLabelPrefab: Prefab = null;

  @property(Node)
  public workLabelList: Node = null;

  @property(Label)
  public timerLabel: Label = null;

  @property
  public gameTime: number = 8; // s

  public currentTime: number = 0;

  @property([CCString])
  public workNameList: Array<string> = [
    "董事长",
    "讨饭",
    "网红",
    "掏粪",
    "专家",
    "捏脚",
    "保安",
    "在编",
    "程序猿",
    "三和大声",
    "爆发户",
  ];

  private usedWorkNames: Set<String> = new Set();

  public static instance: GameManager = null;
  public static getInstance(): GameManager {
    if (!GameManager.instance) {
      GameManager.instance = new GameManager();
    }
    return GameManager.instance;
  }

  protected onLoad(): void {
    this.currentTime = this.gameTime;
  }

  protected start() {
    this.schedule(this.spawnWorkLabel, 1);
  }

  protected update(deltaTime: number) {
    if (this.currentTime > 0) {
      this.currentTime -= deltaTime;
      this.timerLabel.getComponent(Label).string = this.currentTime
        .toFixed(2)
        .toString();
    } else {
      this.currentTime = 0;
      this.timerLabel.getComponent(Label).string = this.currentTime
        .toFixed(2)
        .toString();
    }
  }

  public spawnWorkLabel() {
    if (this.usedWorkNames.size >= this.workNameList.length) {
      // 如果所有工作名称都已使用过，可以重置或停止生成
      return;
    }
    let randomName: string;
    do {
      const randomIndex = Math.floor(Math.random() * this.workNameList.length);
      randomName = this.workNameList[randomIndex];
    } while (this.usedWorkNames.has(randomName));

    this.usedWorkNames.add(randomName);

    const label = instantiate(this.workLabelPrefab);
    label.getComponent(Label).string = randomName;

    this.scheduleOnce(() => {
      label
        .getComponent(BoxCollider2D)
        .size.set(label.getComponent(UITransform).contentSize);
    }, 0);

    label.getComponent(BoxCollider2D).apply();

    this.workLabelList.addChild(label);

    label.setPosition(math.randomRange(-320, 320), 670);
  }

  public restart() {
    director.loadScene("game");
  }
}
